<!-- build time:Tue Dec 17 2019 19:26:42 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="Spring,Spring Boot,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1"><meta name="description" content="内容协商机制是指客户端和服务器端就响应的资源内容进行交涉，然后提供给客户端最为适合的资源。内容协商会以响应资源的语言、字符集、编码方式等作为判断的基准。HTTP请求头中Content-Type，Accept等内容就是内容协商判断的标准。在Spring Boot中，一个完整的内容协商过程如下图所示："><meta name="keywords" content="Spring,Spring Boot"><meta property="og:type" content="article"><meta property="og:title" content="自定义Spring Boot 内容协商"><meta property="og:url" content="http://mrbird.cc/Spring-Boot-Diy-Resolver.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="内容协商机制是指客户端和服务器端就响应的资源内容进行交涉，然后提供给客户端最为适合的资源。内容协商会以响应资源的语言、字符集、编码方式等作为判断的基准。HTTP请求头中Content-Type，Accept等内容就是内容协商判断的标准。在Spring Boot中，一个完整的内容协商过程如下图所示："><meta property="og:locale" content="zh-Hans"><meta property="og:image" content="http://mrbird.cc/img/askfljasdfneiw.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228110016.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228110545.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228142903.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228142955.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228143338.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228143600.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228144601.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228144626.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228145054.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228145215.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228145908.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228185749.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228190930.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190228192419.png"><meta property="og:updated_time" content="2019-10-28T12:14:46.270Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="自定义Spring Boot 内容协商"><meta name="twitter:description" content="内容协商机制是指客户端和服务器端就响应的资源内容进行交涉，然后提供给客户端最为适合的资源。内容协商会以响应资源的语言、字符集、编码方式等作为判断的基准。HTTP请求头中Content-Type，Accept等内容就是内容协商判断的标准。在Spring Boot中，一个完整的内容协商过程如下图所示："><meta name="twitter:image" content="http://mrbird.cc/img/askfljasdfneiw.png"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!1},fancybox:!1,motion:!1}</script><title>自定义Spring Boot 内容协商 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-right:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:1200px}}.header-innerr{position:relative}.header-innerr{padding:20px 0 0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title" style="font-family:Merienda;font-size:1.3rem">MrBird</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section">HOME</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">ARCHIVES</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section">TAGS</a></li><li class="menu-item menu-item-friends"><a href="/friends/" rel="section">FRIENDS</a></li><div class="sidebar-toggle" style="display:none"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"><div class="note info" style="margin:0;letter-spacing:.15px">🐤手把手教你搭建<strong>Spring Cloud微服务权限系统</strong>（从零到部署）：<a style="color:#40dab2;font-weight:600" href="https://www.kancloud.cn/mrbird/spring-cloud" target="_blank">https://www.kancloud.cn/mrbird/spring-cloud</a></div></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/Spring-Boot-Diy-Resolver.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">自定义Spring Boot 内容协商</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">Posted on</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-16T10:08:27+08:00">2018-09-16 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i>&nbsp;&nbsp;Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><p><strong>内容协商</strong>机制是指客户端和服务器端就响应的资源内容进行交涉，然后提供给客户端最为适合的资源。内容协商会以响应资源的语言、字符集、编码方式等作为判断的基准。HTTP请求头中Content-Type，Accept等内容就是内容协商判断的标准。在Spring Boot中，一个完整的内容协商过程如下图所示：</p><a id="more"></a><p><img src="img/askfljasdfneiw.png" alt="askfljasdfneiw.png"></p><p>这个过程的核心组件：</p><table><tr><th>组件</th><th>名称</th><th>说明</th></tr><tr><td>ContentNegotiationManager</td><td>内容协商管理器</td><td>ContentNegotiationStrategy 控制策略</td></tr><tr><td>MediaType</td><td>媒体类型</td><td>HTTP 消息媒体类型，如 text/html</td></tr><tr><td>@RequestMapping#consumes</td><td>消费媒体类型</td><td>请求头 Content-Type 媒体类型映射</td></tr><tr><td>@RequestMapping#produces</td><td>生产媒体类型</td><td>响应头 Content-Type 媒体类型映射</td></tr><tr><td>HttpMessageConverter</td><td>HTTP消息转换器接口</td><td>HTTP 消息转换器，用于反序列化 HTTP 请求或序列化响应</td></tr><tr><td>WebMvcConfigurer</td><td>Web MVC 配置器</td><td>配置 REST 相关的组件</td></tr><tr><td>HandlerMethod</td><td>处理方法</td><td>@RequestMapping 标注的方法</td></tr><tr><td>HandlerMethodArgumentResolver</td><td>处理方法参数解析器</td><td>用于 HTTP 请求中解析 HandlerMethod 参数内容</td></tr><tr><td>HandlerMethodReturnValueHandler</td><td>处理方法返回值解析器</td><td>用于 HandlerMethod 返回值解析为 HTTP 响应内容</td></tr></table><p><code>HttpMessageConverter</code>为HTTP消息转换接口，Spring根据不同的媒体类型进行了相应的实现。比如上图中Accept为application/json，所以在第7步中，会选择使用<code>HttpMessageConverter</code>的实现类<code>MappingJackson2HttpMessageConverter</code>来处理返回值。</p><h2 id="自定义HttpMessageConverter"><a href="#自定义HttpMessageConverter" class="headerlink" title="自定义HttpMessageConverter"></a>自定义HttpMessageConverter</h2><p>除了Spring给我们提供的<code>HttpMessageConverter</code>实现外，我们也可以自定义<code>HttpMessageConverter</code>的实现，来处理一些实际业务需求。</p><p>假如现在要实现一个用于处理 Content-Type 为 text/properties 媒体类型的 HttpMessageConverter 实现类 PropertiesHttpMessageConverter，当我们在请求体中传输下面内容时：</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">name:mrbrid</span><br><span class="line">age:18</span><br></pre></td></tr></table></figure><p></p><p>能够自动转换为Properties对象。</p><p>我们可以参照<code>MappingJackson2HttpMessageConverter</code>的实现方式来进行实现，查看<code>MappingJackson2HttpMessageConverter</code>的原型图：</p><p><img src="img/QQ截图20190228110016.png" alt="QQ截图20190228110016.png"></p><p>所以我们可以通过继承<code>AbstractGenericHttpMessageConverter</code>的方式来实现<code>HttpMessageConverter</code>接口。</p><p>新建Spring Boot项目，版本为2.1.0.RELEASE，并引入<code>spring-boot-starter-web</code>依赖，项目结构如下所示:</p><p><img src="img/QQ截图20190228110545.png" alt="QQ截图20190228110545.png"></p><p>我们在<code>com.example.demo</code>路径下新建<code>converter</code>包，然后创建<code>PropertiesHttpMessageConverter</code>，继承<code>AbstractGenericHttpMessageConverter</code>：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PropertiesHttpMessageConverter</span> <span class="keyword">extends</span> <span class="title">AbstractGenericHttpMessageConverter</span>&lt;<span class="title">Properties</span>&gt; </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">writeInternal</span><span class="params">(Properties properties, Type type, HttpOutputMessage outputMessage)</span> <span class="keyword">throws</span> IOException, HttpMessageNotWritableException </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Properties <span class="title">readInternal</span><span class="params">(Class&lt;? extends Properties&gt; clazz, HttpInputMessage inputMessage)</span> <span class="keyword">throws</span> IOException, HttpMessageNotReadableException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Properties <span class="title">read</span><span class="params">(Type type, Class&lt;?&gt; contextClass, HttpInputMessage inputMessage)</span> <span class="keyword">throws</span> IOException, HttpMessageNotReadableException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>其中<code>readxxx</code>为反序列化过程，即将HTTP请求反序列化为参数的过程；<code>writeInternal</code>为序列化过程，将响应序列化。</p><h3 id="反序列化过程"><a href="#反序列化过程" class="headerlink" title="反序列化过程"></a>反序列化过程</h3><p>我们继续编写<code>PropertiesHttpMessageConverter</code>：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PropertiesHttpMessageConverter</span> <span class="keyword">extends</span> <span class="title">AbstractGenericHttpMessageConverter</span>&lt;<span class="title">Properties</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">writeInternal</span><span class="params">(Properties properties, Type type, HttpOutputMessage outputMessage)</span> <span class="keyword">throws</span> IOException, HttpMessageNotWritableException </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Properties <span class="title">readInternal</span><span class="params">(Class&lt;? extends Properties&gt; clazz, HttpInputMessage inputMessage)</span> <span class="keyword">throws</span> IOException, HttpMessageNotReadableException </span>&#123;</span><br><span class="line">        Properties properties = <span class="keyword">new</span> Properties();</span><br><span class="line">        <span class="comment">// 获取请求头</span></span><br><span class="line">        HttpHeaders headers = inputMessage.getHeaders();</span><br><span class="line">        <span class="comment">// 获取 content-type</span></span><br><span class="line">        MediaType contentType = headers.getContentType();</span><br><span class="line">        <span class="comment">// 获取编码</span></span><br><span class="line">        Charset charset = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (contentType != <span class="keyword">null</span>) &#123;</span><br><span class="line">            charset = contentType.getCharset();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        charset = charset == <span class="keyword">null</span> ? Charset.forName(<span class="string">"UTF-8"</span>) : charset;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取请求体</span></span><br><span class="line">        InputStream body = inputMessage.getBody();</span><br><span class="line">        InputStreamReader inputStreamReader = <span class="keyword">new</span> InputStreamReader(body, charset);</span><br><span class="line">        </span><br><span class="line">        properties.load(inputStreamReader);</span><br><span class="line">        <span class="keyword">return</span> properties;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Properties <span class="title">read</span><span class="params">(Type type, Class&lt;?&gt; contextClass, HttpInputMessage inputMessage)</span> <span class="keyword">throws</span> IOException, HttpMessageNotReadableException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> readInternal(<span class="keyword">null</span>, inputMessage);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>在<code>readInternal</code>方法中，我们获取了HTTP请求体中的输入流和编码，然后调用Properties对象的<code>load</code>方法来将流转换为Properties对象。反序列化过程完成了，我们还需将<code>PropertiesHttpMessageConverter</code>添加到<code>HttpMessageConverter</code>集合中。</p><p>在<code>com.example.demo</code>路径下新建<code>config</code>包，然后创建<code>WebConfigurer</code>配置类：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WebConfigurer</span> <span class="keyword">implements</span> <span class="title">WebMvcConfigurer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">extendMessageConverters</span><span class="params">(List&lt;HttpMessageConverter&lt;?&gt;&gt; converters)</span> </span>&#123;</span><br><span class="line">        converters.add(<span class="keyword">new</span> PropertiesHttpMessageConverter());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>extendMessageConverters</code>方法为<code>WebMvcConfigurer</code>的默认方法，这里我们重写这个方法，用于将<code>PropertiesHttpMessageConverter</code>添加到消息转换器集合中。</p><p>接着创建一个Controller来测试一波，在<code>com.example.demo</code>路径下新建<code>controller</code>包，然后创建<code>TestController</code>：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(value = <span class="string">"test"</span>, consumes = <span class="string">"text/properties"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Properties <span class="title">test</span><span class="params">(@RequestBody Properties properties)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> properties;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>我们通过<code>@GetMapping</code>注解的<code>consumes</code>属性指定了方法接收的媒体类型为<code>text/properties</code>，如果方法能够成功被调用，并且可以返回<code>Properties</code>对象，则说明我们自定义的HTTP消息转换器是可行的。</p><p>启动项目，使用PostMan访问：</p><p><img src="img/QQ截图20190228142903.png" alt="QQ截图20190228142903.png"></p><p>请求头中指定Content-Type为text/properties，请求体内容如下所示:</p><p><img src="img/QQ截图20190228142955.png" alt="QQ截图20190228142955.png"></p><p>访问后，控制台输出错误如下：</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.util.Properties com.example.demo.controller.TestController.test(java.util.Properties)]</span><br></pre></td></tr></table></figure><p></p><p>为什么呢？因为我们在自定义<code>PropertiesHttpMessageConverter</code>的时候需要在其构造器中指定它能够处理的媒体类型，我们查看<code>MappingJackson2HttpMessageConverter</code>的构造器，看看它是怎么实现的：</p><p><img src="img/QQ截图20190228143338.png" alt="QQ截图20190228143338.png"></p><p>所以我们在<code>PropertiesHttpMessageConverter</code>的构造器中添加相应的媒体类型：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">PropertiesHttpMessageConverter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(<span class="keyword">new</span> MediaType(<span class="string">"text"</span>, <span class="string">"properties"</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>这时候，重启项目，再次访问上面的请求，可看到响应如下所示:</p><p><img src="img/QQ截图20190228143600.png" alt="QQ截图20190228143600.png"></p><h3 id="序列化过程"><a href="#序列化过程" class="headerlink" title="序列化过程"></a>序列化过程</h3><p>序列化的过程就是处理HTTP响应的过程，对应<code>PropertiesHttpMessageConverter</code>的<code>writeInternal</code>方法。那为什么我们都还实现这个方法，上面的Controller请求却能返回正常的JSON内容呢？两个原因：</p><ol><li><p>这里我们定义的是REST接口，所以响应默认会被序列化为JSON格式；</p></li><li><p>由于使用<code>converters.add(new PropertiesHttpMessageConverter());</code>这种方式来添加自定义HTTP消息处理器默认会被添加到集合的末尾，在处理JSON响应的时候被排在前面的<code>MappingJackson2HttpMessageConverter</code>优先处理了。</p></li></ol><p>我们可以通过debug来查看<code>PropertiesHttpMessageConverter</code>是否真的被添加到集合末尾了：</p><p><img src="img/QQ截图20190228144601.png" alt="QQ截图20190228144601.png"></p><p><img src="img/QQ截图20190228144626.png" alt="QQ截图20190228144626.png"></p><p>所以我们要换下面这种方式来添加自定义HTTP处理器：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WebConfigurer</span> <span class="keyword">implements</span> <span class="title">WebMvcConfigurer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">extendMessageConverters</span><span class="params">(List&lt;HttpMessageConverter&lt;?&gt;&gt; converters)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// converters.add(new PropertiesHttpMessageConverter());</span></span><br><span class="line">        <span class="comment">// 指定顺序，这里为第一个</span></span><br><span class="line">        converters.add(<span class="number">0</span>, <span class="keyword">new</span> PropertiesHttpMessageConverter());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>我们重启项目，再次debug：</p><p><img src="img/QQ截图20190228145054.png" alt="QQ截图20190228145054.png"></p><p>可看到，<code>PropertiesHttpMessageConverter</code>已经排在第一个了。这时候再次访问上面的请求，响应如下所示:</p><p><img src="img/QQ截图20190228145215.png" alt="QQ截图20190228145215.png"></p><p>没有任何返回值，这是因为我们还没实现<code>writeInternal</code>呢。继续实现<code>writeInternal</code>方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PropertiesHttpMessageConverter</span> <span class="keyword">extends</span> <span class="title">AbstractGenericHttpMessageConverter</span>&lt;<span class="title">Properties</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">writeInternal</span><span class="params">(Properties properties, Type type, HttpOutputMessage outputMessage)</span> <span class="keyword">throws</span> IOException, HttpMessageNotWritableException </span>&#123;</span><br><span class="line">        <span class="comment">// 获取请求头</span></span><br><span class="line">        HttpHeaders headers = outputMessage.getHeaders();</span><br><span class="line">        <span class="comment">// 获取 content-type</span></span><br><span class="line">        MediaType contentType = headers.getContentType();</span><br><span class="line">        <span class="comment">// 获取编码</span></span><br><span class="line">        Charset charset = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (contentType != <span class="keyword">null</span>) &#123;</span><br><span class="line">            charset = contentType.getCharset();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        charset = charset == <span class="keyword">null</span> ? Charset.forName(<span class="string">"UTF-8"</span>) : charset;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取请求体</span></span><br><span class="line">        OutputStream body = outputMessage.getBody();</span><br><span class="line">        OutputStreamWriter outputStreamWriter = <span class="keyword">new</span> OutputStreamWriter(body, charset);</span><br><span class="line"></span><br><span class="line">        properties.store(outputStreamWriter, <span class="string">"Serialized by PropertiesHttpMessageConverter#writeInternal"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>过程和反序化差不多，这里是通过<code>Properties</code>对象的<code>store</code>方法来进行写操作。</p><p>重启项目，再次访问上面的请求，响应如下所示：</p><p><img src="img/QQ截图20190228145908.png" alt="QQ截图20190228145908.png"></p><h2 id="自定义HandlerMethodArgumentResolver"><a href="#自定义HandlerMethodArgumentResolver" class="headerlink" title="自定义HandlerMethodArgumentResolver"></a>自定义HandlerMethodArgumentResolver</h2><p>上面这种方式必须依赖于<code>@RequestBody</code>和<code>@ResponseBody</code>注解，除此之外我们还可以通过自定义<code>HandlerMethodArgumentResolver</code>和<code>HandlerMethodReturnValueHandler</code>实现类的方式来处理内容协商。</p><p><code>HandlerMethodArgumentResolver</code>俗称方法参数解析器，用于解析由<code>@RequestMapping</code>注解（或其派生的注解）所标注的方法的参数。这里我们开始通过实现<code>HandlerMethodArgumentResolver</code>的方式来将HTTP请求体的内容自动解析为Properties对象。</p><p>在<code>com.example.demo</code>路径下新建<code>resolver</code>包，然后创建<code>PropertiesHandlerMethodReturnValueHandler</code>实现<code>HandlerMethodArgumentResolver</code>接口：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PropertiesHandlerMethodArgumentResolver</span> <span class="keyword">implements</span> <span class="title">HandlerMethodArgumentResolver</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter parameter)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Properties.class.equals(parameter.getParameterType());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">resolveArgument</span><span class="params">(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;</span><br><span class="line">        HttpServletRequest request = servletWebRequest.getRequest();</span><br><span class="line">        String contentType = request.getHeader(<span class="string">"Content-Type"</span>);</span><br><span class="line"></span><br><span class="line">        MediaType mediaType = MediaType.parseMediaType(contentType);</span><br><span class="line">        <span class="comment">// 获取编码</span></span><br><span class="line">        Charset charset = mediaType.getCharset() == <span class="keyword">null</span> ? Charset.forName(<span class="string">"UTF-8"</span>) : mediaType.getCharset();</span><br><span class="line">        <span class="comment">// 获取输入流</span></span><br><span class="line">        InputStream inputStream = request.getInputStream();</span><br><span class="line">        InputStreamReader inputStreamReader = <span class="keyword">new</span> InputStreamReader(inputStream, charset);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 输入流转换为 Properties</span></span><br><span class="line">        Properties properties = <span class="keyword">new</span> Properties();</span><br><span class="line">        properties.load(inputStreamReader);</span><br><span class="line">        <span class="keyword">return</span> properties;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>方法<code>supportsParameter</code>用于指定支持解析的参数类型，这里为Properties类型。<code>resolveArgument</code>方法用于实现解析逻辑，解析过程和上面定义的<code>PropertiesHttpMessageConverter</code>的<code>readInternal</code>方法类似。</p><p>接着，我们还需将<code>PropertiesHandlerMethodArgumentResolver</code>添加到Spring自带的<code>HandlerMethodArgumentResolver</code>实现类集合中。值得注意的是，我们不能在配置类<code>WebMvcConfigurer</code>中通过重写<code>addArgumentResolvers</code>的方式来添加，查看该方法源码上的注释：</p><p><img src="img/QQ截图20190228185749.png" alt="QQ截图20190228185749.png"></p><p>大致意思是通过这个方法来添加的方法参数解析器不会覆盖Spring内置的方法参数解析器，如果需要这么做的话，可以直接通过修改<code>RequestMappingHandlerAdapter</code>来实现。</p><p>所以我们可以通过下面这个方式来实现：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WebConfigurer</span> <span class="keyword">implements</span> <span class="title">WebMvcConfigurer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RequestMappingHandlerAdapter requestMappingHandlerAdapter;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostConstruct</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 获取当前 RequestMappingHandlerAdapter 所有的 ArgumentResolver对象</span></span><br><span class="line">        List&lt;HandlerMethodArgumentResolver&gt; argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();</span><br><span class="line">        List&lt;HandlerMethodArgumentResolver&gt; newArgumentResolvers = <span class="keyword">new</span> ArrayList&lt;&gt;(argumentResolvers.size() + <span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 添加 PropertiesHandlerMethodArgumentResolver 到集合第一个位置</span></span><br><span class="line">        newArgumentResolvers.add(<span class="number">0</span>, <span class="keyword">new</span> PropertiesHandlerMethodArgumentResolver());</span><br><span class="line">        <span class="comment">// 将原 ArgumentResolver 添加到集合中</span></span><br><span class="line">        newArgumentResolvers.addAll(argumentResolvers);</span><br><span class="line">        <span class="comment">// 重新设置 ArgumentResolver对象集合</span></span><br><span class="line">        requestMappingHandlerAdapter.setArgumentResolvers(newArgumentResolvers);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>我们在<code>WebConfigurer</code>配置类装配完毕的时候，通过<code>requestMappingHandlerAdapter</code>对象的<code>setArgumentResolvers</code>方法来重新设置方法解析器集合，将<code>PropertiesHandlerMethodArgumentResolver</code>添加到集合的第一个位置。</p><p>之所以要将<code>PropertiesHandlerMethodArgumentResolver</code>添加到第一个位置是因为Properties本质也是一个Map对象，而Spring内置的<code>MapMethodProcessor</code>就是用于处理Map参数类型的，如果不将<code>PropertiesHandlerMethodArgumentResolver</code>优先级提高，那么Properties类型参数会被<code>MapMethodProcessor</code>解析，从而出错。</p><p>配置完毕后，我们改造一下<code>TestController</code>：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// @RestController</span></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(value = <span class="string">"test"</span>, consumes = <span class="string">"text/properties"</span>)</span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Properties <span class="title">test</span><span class="params">(@RequestBody Properties properties)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> properties;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(value = <span class="string">"test1"</span>, consumes = <span class="string">"text/properties"</span>)</span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Properties <span class="title">test1</span><span class="params">(Properties properties)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> properties;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>test1</code>方法的参数没有被<code>@RequestBody</code>标注，启动项目，访问下面这个请求：</p><p><img src="img/QQ截图20190228190930.png" alt="QQ截图20190228190930.png"></p><p>可以看到方法成功执行，并且返回了正确的内容，说明我们自定义的方法参数解析器<code>PropertiesHandlerMethodArgumentResolver</code>是可行的。</p><p>但是方法的返回值还是由<code>PropertiesHttpMessageConverter</code>的<code>writeInternal</code>方法解析的，并且依赖于<code>@ResponseBody</code>注解，接着我们开始实现自定义方法返回值解析器，并且不依赖于<code>@ResponseBody</code>注解。</p><h2 id="自定义HandlerMethodReturnValueHandler"><a href="#自定义HandlerMethodReturnValueHandler" class="headerlink" title="自定义HandlerMethodReturnValueHandler"></a>自定义HandlerMethodReturnValueHandler</h2><p><code>HandlerMethodArgumentResolver</code>俗称方法返回值解析器，用于解析由<code>@RequestMapping</code>注解（或其派生的注解）所标注的方法的返回值。这里我们开始通过实现<code>HandlerMethodReturnValueHandler</code>的方式来自定义一个用于处理返回值类型为Properties类型的解析器。</p><p>在<code>com.example.demo</code>路径下新建<code>handler</code>包，然后创建<code>PropertiesHandlerMethodReturnValueHandler</code>实现<code>HandlerMethodReturnValueHandler</code>：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PropertiesHandlerMethodReturnValueHandler</span> <span class="keyword">implements</span> <span class="title">HandlerMethodReturnValueHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsReturnType</span><span class="params">(MethodParameter returnType)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Properties.class.equals(returnType.getMethod().getReturnType());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleReturnValue</span><span class="params">(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Properties properties = (Properties) returnValue;</span><br><span class="line"></span><br><span class="line">        ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;</span><br><span class="line"></span><br><span class="line">        HttpServletResponse response = servletWebRequest.getResponse();</span><br><span class="line">        ServletServerHttpResponse servletServerHttpResponse = <span class="keyword">new</span> ServletServerHttpResponse(response);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取请求头</span></span><br><span class="line">        HttpHeaders headers = servletServerHttpResponse.getHeaders();</span><br><span class="line"></span><br><span class="line">        MediaType contentType = headers.getContentType();</span><br><span class="line">        <span class="comment">// 获取编码</span></span><br><span class="line">        Charset charset = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (contentType != <span class="keyword">null</span>) &#123;</span><br><span class="line">            charset = contentType.getCharset();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        charset = charset == <span class="keyword">null</span> ? Charset.forName(<span class="string">"UTF-8"</span>) : charset;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取请求体</span></span><br><span class="line">        OutputStream body = servletServerHttpResponse.getBody();</span><br><span class="line">        OutputStreamWriter outputStreamWriter = <span class="keyword">new</span> OutputStreamWriter(body, charset);</span><br><span class="line"></span><br><span class="line">        properties.store(outputStreamWriter, <span class="string">"Serialized by PropertiesHandlerMethodReturnValueHandler#handleReturnValue"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>supportsReturnType</code>方法指定了处理返回值的类型，<code>handleReturnValue</code>方法用于处理返回值，这里的逻辑和<code>PropertiesHttpMessageConverter</code>的<code>writeInternal</code>方法基本一致，不再赘述。</p><p>接着将<code>PropertiesHandlerMethodReturnValueHandler</code>添加到到Spring自带的<code>HandlerMethodReturnValueHandler</code>实现类集合中，添加方式和自定义<code>HandlerMethodArgumentResolver</code>一致：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WebConfigurer</span> <span class="keyword">implements</span> <span class="title">WebMvcConfigurer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RequestMappingHandlerAdapter requestMappingHandlerAdapter;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostConstruct</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 获取当前 RequestMappingHandlerAdapter 所有的 ArgumentResolver对象</span></span><br><span class="line">        List&lt;HandlerMethodArgumentResolver&gt; argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();</span><br><span class="line">        List&lt;HandlerMethodArgumentResolver&gt; newArgumentResolvers = <span class="keyword">new</span> ArrayList&lt;&gt;(argumentResolvers.size() + <span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 添加 PropertiesHandlerMethodArgumentResolver 到集合第一个位置</span></span><br><span class="line">        newArgumentResolvers.add(<span class="number">0</span>, <span class="keyword">new</span> PropertiesHandlerMethodArgumentResolver());</span><br><span class="line">        <span class="comment">// 将原 ArgumentResolver 添加到集合中</span></span><br><span class="line">        newArgumentResolvers.addAll(argumentResolvers);</span><br><span class="line">        <span class="comment">// 重新设置 ArgumentResolver对象集合</span></span><br><span class="line">        requestMappingHandlerAdapter.setArgumentResolvers(newArgumentResolvers);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取当前 RequestMappingHandlerAdapter 所有的 returnValueHandlers对象</span></span><br><span class="line">        List&lt;HandlerMethodReturnValueHandler&gt; returnValueHandlers = requestMappingHandlerAdapter.getReturnValueHandlers();</span><br><span class="line">        List&lt;HandlerMethodReturnValueHandler&gt; newReturnValueHandlers = <span class="keyword">new</span> ArrayList&lt;&gt;(returnValueHandlers.size() + <span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 添加 PropertiesHandlerMethodReturnValueHandler 到集合第一个位置</span></span><br><span class="line">        newReturnValueHandlers.add(<span class="number">0</span>, <span class="keyword">new</span> PropertiesHandlerMethodReturnValueHandler());</span><br><span class="line">        <span class="comment">// 将原 returnValueHandlers 添加到集合中</span></span><br><span class="line">        newReturnValueHandlers.addAll(returnValueHandlers);</span><br><span class="line">        <span class="comment">// 重新设置 ReturnValueHandlers对象集合</span></span><br><span class="line">        requestMappingHandlerAdapter.setReturnValueHandlers(newReturnValueHandlers);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>配置好后，我们将<code>TestController</code>的<code>test1</code>方法的<code>@ResponseBody</code>注解去掉，重启项目，再次访问:</p><p><img src="img/QQ截图20190228192419.png" alt="QQ截图20190228192419.png"></p><p>可以看到，返回值成功被<code>PropertiesHandlerMethodReturnValueHandler</code>的<code>handleReturnValue</code>方法解析了。</p><p>但是这里还有一个问题，我们查看控制台，会发现如下异常:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">javax.servlet.ServletException: Circular view path [test1]: would dispatch back to the current handler URL [/test1] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)</span><br><span class="line">	at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:209) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:147) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:890) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875) ~[spring-webmvc-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_171]</span><br><span class="line">	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_171]</span><br><span class="line">	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.12.jar:9.0.12]</span><br><span class="line">	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_171]</span><br></pre></td></tr></table></figure><p>这是因为，在Spring中如果Controller中的方法没有被<code>@ResponseBody</code>标注的话，默认会把返回值当成视图的名称，而这里我们并不希望解析的Properties值被当成视图名称，所以我们需要在<code>PropertiesHandlerMethodReturnValueHandler</code>的<code>handleReturnValue</code>方法最后一行添加如下代码：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 告诉 Spring MVC 请求已经处理完毕</span></span><br><span class="line">mavContainer.setRequestHandled(<span class="keyword">true</span>);</span><br></pre></td></tr></table></figure><p>这行代码告诉Spring，请求已经成功完成了，无需进行后续的处理。重启项目再次访问上面的请求，控制台便不再抛异常了。</p><blockquote><p>源码链接：<a href="https://github.com/wuyouzhuguli/SpringAll/tree/master/47.Spring-Boot-Content-Negotiation" target="_blank" rel="noopener">https://github.com/wuyouzhuguli/SpringAll/tree/master/47.Spring-Boot-Content-Negotiation</a></p></blockquote><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787"><div>请作者喝瓶肥宅水~</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">￥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接：</strong> <a href="http://mrbird.cc/Spring-Boot-Diy-Resolver.html" title="自定义Spring Boot 内容协商">http://mrbird.cc/Spring-Boot-Diy-Resolver.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/Spring/" rel="tag"># Spring</a> <a href="/tags/Spring-Boot/" rel="tag"># Spring Boot</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/Spring-Boot-Hibernate-Validator-Params-Check.html" rel="next" title="Spring Boot配合Hibernate Validator参数校验"><i class="fa fa-chevron-left"></i> Spring Boot配合Hibernate Validator参数校验</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/Spring-Boot-Deal-CORS.html" rel="prev" title="Spring Boot 中处理跨域">Spring Boot 中处理跨域 <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#42b983!important}.valine .vinfo .col{text-align:left;margin-left:-27rem}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#42b983}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#42b983;border-color:#42b983;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#42b983}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#42b983}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="http://schema.org/Person"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><h3 class="author__name" itemprop="name">MrBird's Blog</h3><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__urls-wrapper"><button class="btn btn--inverse">Follow</button><ul class="author__urls social-icons"><li><a href="http://map.baidu.com/?newmap=1&s=s%26wd%3D%E7%A6%8F%E5%B7%9E%E5%B8%82%26c%3D300&from=alamap&tpl=mapcity" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-map-marker" aria-hidden="true"></i>&nbsp;&nbsp;FuZhou,CN</a></li><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i>&nbsp;&nbsp;Love</a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-chain" aria-hidden="true"></i>&nbsp;&nbsp;FEBS</a></li><li><a href="/atom.xml" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-rss" aria-hidden="true"></i>&nbsp;&nbsp;RSS</a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i>&nbsp;&nbsp;Gitee</a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i>&nbsp;&nbsp;GitHub</a></li><li><a href="javascript:;" class="popup-trigger"><i class="fa fa-fw fa-search" aria-hidden="true"></i>&nbsp;&nbsp;Search</a></li></ul></div></div></div><script>var $urls=$(".author__urls").find("a");$urls.each(function(){var o=$(this);o.mouseenter(function(){o.css({color:"#414547"})}),o.mouseleave(function(){o.css({color:""})})})</script></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义HttpMessageConverter"><span class="nav-number">1.</span> <span class="nav-text">自定义HttpMessageConverter</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#反序列化过程"><span class="nav-number">1.1.</span> <span class="nav-text">反序列化过程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#序列化过程"><span class="nav-number">1.2.</span> <span class="nav-text">序列化过程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义HandlerMethodArgumentResolver"><span class="nav-number">2.</span> <span class="nav-text">自定义HandlerMethodArgumentResolver</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义HandlerMethodReturnValueHandler"><span class="nav-number">3.</span> <span class="nav-text">自定义HandlerMethodReturnValueHandler</span></a></li></ol></div></div></section></div></aside></div></main><footer id="footer" class="footer" onselectstart="return!1"><div class="footer-inner"><div class="copyright">&copy; 2016 - <span itemprop="copyrightYear">2019</span>&nbsp;&nbsp; <span class="author" itemprop="copyrightHolder">MrBird</span>&nbsp;&nbsp;|<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>&nbsp;&nbsp;UV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span> &nbsp;&nbsp;PV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span></div></div></footer><div class="back-to-top"><span style="font-family:'Source Sans Pro','Helvetica Neue',Arial,sans-serif;font-size:1.2em;font-weight:600">TOP</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->